package asdf.trial.aio;

import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Future;

public class Server
{

    public static void main(String[] args)
    {

        try {
            AsynchronousServerSocketChannel serverSocket = AsynchronousServerSocketChannel.open();
            serverSocket.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
            serverSocket.bind(new InetSocketAddress(2222));
            serverSocket.accept(serverSocket, new ACompletionHandler());

        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    public static class ACompletionHandler implements CompletionHandler<AsynchronousSocketChannel,
            AsynchronousServerSocketChannel>
    {

        @Override
        public void completed(
                AsynchronousSocketChannel result, AsynchronousServerSocketChannel attachment)
        {

            ByteBuffer bb = ByteBuffer.allocateDirect(8);
            result.read(bb, attachment,
                        new CompletionHandler<Integer, AsynchronousServerSocketChannel>()
                        {

                            @Override
                            public void completed(Integer result, AsynchronousServerSocketChannel attachment) {}

                            @Override
                            public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) {}

                        });
        }

        @Override
        public void failed(
                Throwable exc, AsynchronousServerSocketChannel attachment)
        {
            exc.printStackTrace();
        }
    }

}
